<template>
  <div class="flex justify-end mb-2"></div>
  <BaseTable bordered :data-source="dataSource" column-code="000111" :pagination="false" :scroll="{ x: 1400 }" :row-class-name="getRowClassName">
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'icd10TypeName'">
        <EditCell title="诊断类型">
          <a-select
            id="DT00033"
            v-model:value="record.diagnosisType"
            :disabled="record.beDel === '1' && getSystemConfig('INP_DOCTOR_ALLOW_MODIFY_OUTP_ICD10') !== '1'"
            placeholder="请选择"
            @change="(_, option) => onTypeChange(option, record)"
          >
            <a-select-option v-for="item in diagnosisData" :key="item.id" :disabled="item.disabled" :text="item.dictItemName" :value="item.dictItemCode">
              {{ item.dictItemName }}
            </a-select-option>
          </a-select>
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'diagnosisCategory'">
        <EditCell title="诊断类别 中医/西医">
          <a-select v-model:value="record.diagnosisCategory" :disabled="record.beDel === '1'" placeholder="请选择" @change="onResetDiagnosis(record)">
            <a-select-option value="0">西医</a-select-option>
            <a-select-option value="1">中医</a-select-option>
          </a-select>
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'icd10Name'">
        <EditCell title="诊断名称">
          <SelectTable
            v-if="record.diagnosisCategory === '1'"
            v-model:value="record.icd10Name"
            :disabled="record.beDel === '1'"
            type="中医诊断"
            @select="onSelectDiagnosis($event, record)"
          />
          <SelectTable v-else v-model:value="record.icd10Name" type="诊断" :disabled="record.beDel === '1'" @select="onSelectDiagnosis($event, record)" />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'diagnosisDescription'">
        <EditCell title="诊断描述">
          <a-input v-model:value="record.diagnosisDescription" v-input-selection :disabled="record.beDel === '1'" placeholder="请输入" />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'partId'">
        <EditCell title="部位">
          <!-- <a-select
            v-model:value="record.partId"
            placeholder="请选择"
            :disabled="record.beDel === '1'"
            :options="positionList"
            allow-clear
            @change="onSelectPart(record)"
          /> -->
          <SelectPartTags
            :value="{ partCode: record.partIdList, partName: record.partName }"
            multiple
            allow-clear
            show-new
            :input-or-textarea="true"
            type="部位"
            @select=";(record.partIdList = $event.partCode), (record.partName = $event.partName)"
          />
        </EditCell>
      </template>
      <template v-else-if="column.dataIndex === 'checkinConditionName'">
        <!-- :prompt="record.icd10TypeName !== '入院诊断-其他诊断' && record.icd10TypeName !== '入院诊断-主要诊断' ? '' : '请选择'"
        :disabled="record.icd10TypeName !== '入院诊断-其他诊断' && record.icd10TypeName !== '入院诊断-主要诊断'" -->
        <EditCell title="入院病情">
          <SelectItem
            v-model:value="record.checkinConditionCode"
            class="!min-w-full"
            type="DT00265"
            :prompt="isDiagnosis(record) ? '' : '请选择'"
            :disabled="isDiagnosis(record)"
            @change="(_, option) => (record.checkinConditionName = option.label)"
          />
        </EditCell>
      </template>
      <template v-else-if="column.dataIndex === 'checkoutConditionName'">
        <!-- :disabled="record.icd10TypeName !== '出院诊断-其他诊断' && record.icd10TypeName !== '出院诊断-主要诊断'" -->
        <EditCell title="出院病情">
          <SelectItem
            v-model:value="record.checkoutConditionCode"
            class="!min-w-full"
            type="DT00266"
            :disabled="isDiagnosis(record)"
            @change="(_, option) => (record.checkoutConditionName = option.label)"
          />
        </EditCell>
      </template>
      <template v-else-if="column.dataIndex === 'createTime'">
        <EditCell title="诊断时间">
          <a-date-picker
            v-model:value="record.createTime"
            class="w-full"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择"
          />
        </EditCell>
      </template>
      <template v-else-if="column.dataIndex === 'action'">
        <BaseButton confirm-text="确认删除？" type="link" size="small" :disabled="record.beDel === '1' || store.radioKey" danger @click="onDelete(record)"
          >删除</BaseButton
        >
      </template>
    </template>
    <template #footer>
      <div v-if="isMedicalRecord" class="w-full border-b border-gray-200 p-2">
        入院病情：<span class="mr-5">1.有</span> <span class="mr-5">2.临床未确定</span><span class="mr-5"> 3.情况不明</span><span class="mr-5">4.无</span>
        <span class="mx-2"></span> 出院情况： <span class="mr-5">1.治愈</span> <span class="mr-5">2.好转</span> <span class="mr-5">3.未愈</span>
        <span class="mr-5">4.死亡</span> <span class="mr-5">5.其他</span>
      </div>
      <div class="text-center sticky bottom-0 py-2">
        <a-button type="primary" class="mr-2" ghost :icon="h(PlusOutlined)" :disabled="(store.radioKey && !isMedicalRecord) || isSubmit" @click="onAdd()">
          新增一行
        </a-button>
        <a-button type="primary" :icon="h(SaveOutlined)" :disabled="(store.radioKey && !isMedicalRecord) || isSubmit" @click="onSave()"> 保存 </a-button>
      </div>
    </template>
  </BaseTable>
</template>
<script setup>
import { ref, watch, h, onMounted } from 'vue'
import { PlusOutlined, SaveOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'
import useStore from '../../store'

const props = defineProps({
  isMedicalRecord: {
    type: Boolean,
    default: false
  },
  isSubmit: {
    type: Boolean,
    default: false
  },
  isMedicalInplsh: {
    type: String,
    default: ''
  }
})
const { empName } = useUserStore()
const store = useStore()
const dataSource = ref([])
const diagnosisData = ref([])
const isDiagnosis = (row) => {
  return row.icd10TypeName === '门(急)诊诊断-其他诊断' || row.icd10TypeName === '门(急)诊诊断-主要诊断'
}
// const positionList = ref([])
const defaultRow = () => ({
  diagnosisCategory: '0',
  isNew: true,
  inpLsh: props.isMedicalRecord ? props.isMedicalInplsh : store.currentPatient.inplsh,
  createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  diagnosisDoctorName: empName
})
const getData = async () => {
  if (props.isMedicalRecord) {
    if (!props.isMedicalInplsh) {
      return (dataSource.value = [])
    }
  } else {
    if (!store.currentPatient.inplsh) {
      return (dataSource.value = [])
    }
  }
  const res = await post('/inp/zyys/getPatientDiagnosisInfoList', {
    inplsh: props.isMedicalRecord ? props.isMedicalInplsh : store.currentPatient.inplsh
  })
  if (res.code !== 0) return
  if (res.data.length === 0) {
    dataSource.value = [{ key: 'row-0', ...defaultRow() }]
  } else {
    dataSource.value = res.data.map((item) => {
      item.diagnosisCategory = item.diagnosisCategory ? item.diagnosisCategory : '0'
      return item
    })
    if (props.isMedicalRecord) {
      dataSource.value = dataSource.value.filter((item) => !item.icd10TypeName.includes('门(急)诊诊断') && !item.icd10TypeName.includes('入院诊断'))
    }
  }
}
//获取诊断类型
const getDiagnosisData = async () => {
  const res = await post('/operation/opex/getDictCommonItemList', {
    dictCommonCode: 'DT00033',
    status: 1
  })
  if (res.code !== 0) return
  diagnosisData.value = res.data.map((item) => {
    return {
      ...item,
      disabled: item.dictItemName.includes('门(急)诊') && getSystemConfig('INP_DOCTOR_ALLOW_MODIFY_OUTP_ICD10') !== '1'
    }
  })
}
//获取部位集合
// const getPositionList = async () => {
//   const { code, data } = await post('/operation/opex/getDictPartList', {
//     zjm: '',
//     pageNum: 1,
//     pageSize: 999
//   })
//   if (code !== 0) return
//   positionList.value = data.map((item) => {
//     return {
//       value: item.id,
//       label: item.partName
//     }
//   })
// }
// 选择部位
// const onSelectPart = (record) => {
//   if (!record?.partId) {
//     record.partId = null
//   }
// }

//选择诊断项目
const onSelectDiagnosis = (selected, record) => {
  if (record.diagnosisCategory === '1') {
    //中医
    record.icd10Code = selected.dm
    record.icd10Name = selected.mc
  } else {
    //西医
    record.icd10Code = selected.nmiIcd10Code
    record.zzdm = selected.zddm
    record.icd10Name = selected.zdmc
  }
}
const onResetDiagnosis = (record) => {
  record.icd10Code = ''
  record.icd10Name = ''
}
const onTypeChange = (option, record) => {
  record.icd10TypeName = option.text
  if (option.text === '出院诊断-主要诊断' && getSystemConfig('INP_DISCHARGE_DIAGNOSIS_CITE_ADMISSION_DIAGNOSIS') === '1') {
    const ryzd = dataSource.value.find((item) => item.icd10TypeName === '入院诊断-主要诊断') || {}
    record.icd10Name = ryzd.icd10Name
    record.icd10Code = ryzd.icd10Code
  }
}
const onDelete = async (row) => {
  if (row.isNew) {
    dataSource.value = dataSource.value.filter((item) => item.key !== row.key)
  } else {
    const { code, msg } = await post('/inp/zyys/doDelPatientDiagnosis', { id: row.id })
    if (code !== 0) return message.error(msg || '删除失败')
    message.success('删除成功')
    getData()
  }
}
const onAdd = () => {
  const key = `row-${dataSource.value.length}`
  dataSource.value.push({ key, ...defaultRow() })
}

const onSave = async () => {
  dataSource.value.forEach((item) => {
    if (item.partId === null) {
      item.partId = ''
    }
  })
  const { code, msg } = await post('/inp/zyys/doSavePatientDiagnosisList', dataSource.value)
  if (code !== 0) return message.error(msg || '保存失败')
  message.destroy()
  message.success('保存成功')
  getData()
}

const getRowClassName = (row) => {
  return {
    'table-row-new': row.isNew
    // 'table-row-disabled': row.beDel === '1'
  }
}

watch(
  () => store.currentPatient.inplsh,
  () => getData(),
  { immediate: true }
)

onMounted(() => {
  // getPositionList()
  getDiagnosisData()
})
</script>
<style scoped>
:deep(.ant-table-footer) {
  padding: 0 !important;
}
</style>
